<!-- 选择学生组件 -->
<template>
  <div class="type-class-box" ref="studentRef">
    <el-tabs v-model="activeTab" @tab-change="onChangTab">
      <el-tab-pane
        label="选择班级"
        :name="2"
        :disabled="getCheckedStudentList().length > 0"
      ></el-tab-pane>
      <el-tab-pane
        label="选择学生"
        :name="1"
        :disabled="activeClassList.length > 0"
      ></el-tab-pane>
    </el-tabs>

    <el-scrollbar height="70vh" class="class-scroll" v-if="activeTab === 2">
      <div
        class="class-box"
        v-for="(classType, index) in classTypeList"
        :key="index"
      >
        <div class="tool-box flex-between">
          <el-checkbox
            v-model="classType.checkAll"
            @change="param => onCheckAllClass(param, index)"
            :disabled="!classType.classList.length"
          >
            {{ classType.text }}
          </el-checkbox>
        </div>
        <div class="class-list">
          <div
            v-for="(classItem, classIndex) in classType.classList"
            class="class-select hover"
            :class="[
              activeClassList.indexOf(classItem.value) !== -1 &&
                'class-select-active'
            ]"
            @click="onSelectClassTab1(classItem, index)"
            :key="classIndex"
          >
            {{ classItem.label }}
          </div>
          <div v-if="!classType.classList.length" class="text">
            暂无{{ classType.text }}
          </div>
        </div>
      </div>
    </el-scrollbar>
    <template v-else-if="activeTab === 1">
      <div class="list-box flex">
        <div class="box-left flex-column">
          <div
            class="list-item text-ellipsis hover"
            :class="[
              activeClass?.value === classItem.value && 'list-item-active'
            ]"
            :title="classItem.label"
            v-for="(classItem, index) in showClassList"
            :key="index"
            @click="onSelectClassTab2(classItem)"
          >
            {{ classItem.label }}
            <div class="dot" v-if="getCheckedNum(classItem).length">
              {{ getCheckedNum(classItem).length }}
            </div>
          </div>
        </div>
        <div class="box-right">
          <div class="flex-between tool-box">
            <el-checkbox
              class="select-layer"
              @change="onChangeCheckAll"
              v-model="checkAllStudent"
            >
              全选
            </el-checkbox>
            <el-checkbox class="select-layer" v-model="checkLayer">
              启动分层
            </el-checkbox>
          </div>
          <div class="student-box flex" v-if="!checkLayer">
            <el-scrollbar height="64.4vh" class="student-list">
              <div
                v-for="(student, index) in showAllStudentList"
                class="student-select hover"
                :class="[student.checked && 'class-select-active']"
                @click="onCheckStudent(student)"
                :key="index"
              >
                {{ student.student_name }}
              </div>
            </el-scrollbar>
          </div>
          <el-scrollbar height="64.4vh" v-else>
            <div
              class="student-box"
              v-for="(checkedItem, index) in activeClass.checkedList"
              :key="index"
            >
              <el-checkbox
                class="select-layer"
                @change="param => onChangeCheckLayerAll(param, index)"
                v-model="activeClass.checkedList[index]"
                :disabled="!activeClass.layerList[index]?.length"
              >
                {{
                  index === 0
                    ? '待分层学生'
                    : String.fromCharCode(index + 64) + '层学生'
                }}
              </el-checkbox>
              <div class="layer-list flex">
                <div
                  v-for="(student, studentIndex) in activeClass.layerList[
                    index
                  ]"
                  class="student-select hover"
                  :class="[student.checked && 'student-select-active']"
                  @click="onCheckStudent(student)"
                  :key="studentIndex"
                >
                  {{ student.student_name }}
                </div>
                <span v-if="!activeClass.layerList[index]?.length"
                  >此层无学生</span
                >
              </div>
            </div>
          </el-scrollbar>
        </div>
      </div>
    </template>
  </div>
</template>

<script setup>
import { ref, defineExpose, watch, computed, nextTick, onMounted } from 'vue'
import dayjs from 'dayjs'
import { storeToRefs } from 'pinia'
import { useAuthStore } from '@/stores/auth-store'
import { getLayeredStudentList } from '@/apis/assignment/index'
import { CLASS_TYPE } from '@/views/assignment/util'
import { MsgTypeEnum } from '../constant'

const classTypeList = defineModel('classTypeList')
const activeTab = defineModel('activeTab')
const activeClassList = defineModel('activeClassList')

const props = defineProps({
  selectClassInfo: { default: () => [] },
  msgType: { type: Number, required: true },
  subject: { type: Number, default: 0 }
})

const isHomeworkMsg = computed(() => props.msgType === MsgTypeEnum.HOMEWORK)

const studentRef = ref()
const authStore = useAuthStore()
const {
  nowGlobalRole,
  userInfo,
  tbAdminAndTeachingClassList,
  tbTargetClassList,
  smartRoomClassList
} = storeToRefs(authStore)
const { getTeachingInfo } = authStore

const activeClass = ref() // tab2 当前班级

const checkLayer = ref(false) // 启动分层
const checkAllStudent = ref(false) // 全选学生

/**
 * tab1展示班级列表
 */
classTypeList.value = [
  {
    text: '行政班',
    checkAll: false,
    classList: []
  },
  {
    text: '教学班',
    checkAll: false,
    classList: []
  },
  {
    text: '靶向班',
    checkAll: false,
    classList: []
  },
  {
    text: '智习班',
    checkAll: false,
    classList: []
  }
]

/**
 * tab2展示左侧班级列表
 */
const showClassList = computed(() => {
  return [
    ...classTypeList.value[0].classList,
    ...classTypeList.value[1].classList,
    ...classTypeList.value[2].classList,
    ...classTypeList.value[3].classList
  ]
})

const onChangTab = () => {
  activeClass.value = showClassList.value[0]
  if (!activeClass.value.layerList.length) {
    getLayeredStudentListInfo()
  }
}

/**
 *  tab1 选中/取消选中班级
 * @param {*} classItem
 */
const onSelectClassTab1 = (classItem, typeIndex) => {
  if (classItem) {
    let index = activeClassList.value.indexOf(classItem.value)
    if (index === -1) {
      activeClassList.value.push(classItem.value)
    } else {
      activeClassList.value.splice(index, 1)
    }
  }

  let res = classTypeList.value[typeIndex].classList.find(
    item => activeClassList.value.indexOf(item.value) === -1
  )
  classTypeList.value[typeIndex].checkAll = res ? false : true
}

/**
 * tab2 获取分层数据
 */
const getLayeredStudentListInfo = async (typeClass, studentIds) => {
  const paramClass = typeClass || activeClass.value
  const res = await getLayeredStudentList({
    class_id: String(paramClass.value),
    subject_id: props.subject || -1,
    task_from: 1,
    layer_type: 3,
    start_time: dayjs().subtract(6, 'month').startOf('date').unix(),
    end_time: dayjs().unix(),
    teacher_id: userInfo.value.userId,
    school_id: userInfo.value.school_id
  })
  const { students, a_students, b_students, c_students } = res.data
  paramClass.layerList = [
    (students || []).map(student => ({
      ...student,
      checked: studentIds
        ? studentIds.indexOf(student.student_id) !== -1
        : false
    })),
    (a_students || []).map(student => ({
      ...student,
      checked: studentIds
        ? studentIds.indexOf(student.student_id) !== -1
        : false
    })),
    (b_students || []).map(student => ({
      ...student,
      checked: studentIds
        ? studentIds.indexOf(student.student_id) !== -1
        : false
    })),
    (c_students || []).map(student => ({
      ...student,
      checked: studentIds
        ? studentIds.indexOf(student.student_id) !== -1
        : false
    }))
  ]
}

/**
 * tab2 选中班级
 */
const onSelectClassTab2 = async classItem => {
  activeClass.value = classItem
  !activeClass.value.layerList.length && (await getLayeredStudentListInfo())
}

const getCheckedNum = classItem => {
  let list = []
  if (classItem.layerList.length) {
    classItem.layerList.forEach(layer => {
      list.push(...layer.filter(student => student.checked))
    })
  }
  return list
}

const getCheckedStudentList = () => {
  let list = []
  classTypeList.value.forEach(classType => {
    classType.classList.forEach(classItem => {
      list.push(...getCheckedNum(classItem))
    })
  })
  return list
}

// 全部全选
const onChangeCheckAll = param => {
  if (!activeClass.value.layerList.length) return
  activeClass.value.layerList.forEach(layer => {
    layer.forEach(student => (student.checked = param))
  })
}

// tab1 全选班级类型
const onCheckAllClass = (param, index) => {
  classTypeList.value[index].classList.forEach(classItem => {
    let classIndex = activeClassList.value.indexOf(classItem.value)
    if (param && classIndex === -1) {
      activeClassList.value.push(classItem.value)
    } else if (!param && classIndex !== -1) {
      activeClassList.value.splice(classIndex, 1)
    }
  })
}

// 分层全选
const onChangeCheckLayerAll = (param, index) => {
  activeClass.value.checkedList[index] = param
  activeClass.value.layerList[index].forEach(
    student => (student.checked = param)
  )
}

const onCheckStudent = student => {
  student.checked = !student.checked
}

const showAllStudentList = computed(() => {
  if (activeClass.value) {
    let list = []
    activeClass.value.layerList.forEach(layer => list.push(...layer))
    return list
  }
  return []
})

watch(
  () => activeClass.value?.layerList,
  () => {
    activeClass.value.layerList.forEach((layer, index) => {
      if (layer.length && !layer.filter(student => !student.checked).length) {
        activeClass.value.checkedList[index] = true
      } else {
        activeClass.value.checkedList[index] = false
      }
    })
  },
  {
    deep: true
  }
)
watch(
  () => showAllStudentList.value,
  () => {
    if (!showAllStudentList.value.length) return
    if (showAllStudentList.value.find(student => !student.checked)) {
      checkAllStudent.value = false
    } else {
      checkAllStudent.value = true
    }
  },
  {
    deep: true
  }
)

const getAllClassList = subjectId => {
  const allClassList = []
  const classTypeMap = {
    'class_category|1001': 1,
    'class_category|1002': 2
  }
  // 行政及教学班
  if (tbAdminAndTeachingClassList.value?.length) {
    const result = []
    // TODO 后续加上切换学校后处理多个学校的情况，目前暂时只取第一个学校的数据
    const [school] = tbAdminAndTeachingClassList.value
    school?.grade_list.forEach(grade => {
      const classList = grade.class_list.filter(cls => {
        if (subjectId === 0) {
          return true
        }
        if (!cls.subject_list) {
          return false
        }
        return cls?.subject_list.some(subject => subject.num === subjectId)
      })
      if (classList.length > 0) {
        result.push({
          value: grade.grade_num,
          label: grade.grade_name,
          grade_id: grade.grade_id,
          children: classList.map(cls => ({
            value: cls.id,
            label: cls.class_name,
            class_type: classTypeMap[cls.class_type]
          }))
        })
      }
    })
    allClassList.push(...result)
  }
  // 靶向班
  const targetClassList = tbTargetClassList.value?.filter(v =>
    subjectId ? v.subject_num === subjectId : true
  )
  allClassList.push(...targetClassList)
  allClassList.push(...smartRoomClassList.value)
  return allClassList
}

// 初始化班级数据
const initData = async () => {
  await getTeachingInfo(nowGlobalRole.value.role_code)
  // 获取根据全局学段、发通知选中学科筛选后的班级列表
  const subject = isHomeworkMsg.value ? props.subject : 0
  const data = getAllClassList(subject)
  console.log('!!!!!!!!!!!', subject, data)
  let adminTeachClass = data.filter(item => item.value > 0)
  let targetClass = data.filter(item => item.value == 0)
  let smartClass = data.filter(item => item.value == '-1')

  let classlist = []
  adminTeachClass.forEach(item => {
    item.children.forEach(child => {
      classlist.push({
        ...child,
        label: item.label + child.label,
        class_type: child.class_type
      })
    })
  })
  targetClass.forEach(item => {
    item.children.forEach(child => {
      classlist.push({
        ...child,
        class_type: CLASS_TYPE.TargetClass
      })
    })
  })
  smartClass.forEach(item => {
    item.children.forEach(child => {
      classlist.push({
        ...child,
        class_type: CLASS_TYPE.SmartClass
      })
    })
  })

  classlist.forEach(item => {
    switch (item.class_type) {
      case CLASS_TYPE.AdminClass:
        classTypeList.value[0].classList.push({
          ...item,
          checkedList: [false, false, false, false],
          layerList: []
        })
        break
      case CLASS_TYPE.TeachClass:
        classTypeList.value[1].classList.push({
          ...item,
          checkedList: [false, false, false, false],
          layerList: []
        })
        break
      case CLASS_TYPE.TargetClass:
        classTypeList.value[2].classList.push({
          ...item,
          checkedList: [false, false, false, false],
          layerList: []
        })
        break
      case CLASS_TYPE.SmartClass:
        classTypeList.value[3].classList.push({
          ...item,
          checkedList: [false, false, false, false],
          layerList: []
        })
        break
    }
  })

  // 有初始值的情况下
  // 选择的是全班
  if (
    props.selectClassInfo.length &&
    !props.selectClassInfo[0].student_ids?.length
  ) {
    activeClassList.value = props.selectClassInfo.map(classItem =>
      String(classItem.class_id)
    )
    nextTick(() => {
      classTypeList.value.forEach((_, index) => {
        onSelectClassTab1(null, index)
      })
    })
    activeTab.value = 2
  }
  // 选择的是学生
  else if (props.selectClassInfo.length) {
    for (let i = 0; i < props.selectClassInfo.length; i++) {
      const classItem = props.selectClassInfo[i]
      let item = null
      classTypeList.value.find(typeList => {
        const res = typeList.classList.find(
          list => list.value == classItem.class_id
        )
        item = res || null
        return item
      })
      if (item) {
        await getLayeredStudentListInfo(item, classItem.student_ids)
      }
    }

    onChangTab()
    activeTab.value = 1
  }
}

onMounted(() => {
  initData()
})

defineExpose({ getCheckedStudentList })
</script>

<!-- eslint-disable -->
<style lang="less" scoped>
.type-class-box {
  height: 100%;
  font-size: 18px;
  :deep(.el-tabs__header) {
    margin-bottom: 20px;
    .el-tabs__nav-wrap {
      --el-font-size-base: 18px;
      &::after {
        height: 0;
      }
      .el-tabs__active-bar {
        width: 10px !important;
        margin-left: 17%;
        bottom: 3px;
      }
    }
  }
  .class-scroll {
    height: auto;
    // :deep(.el-scrollbar__view) {}
  }
  .text {
    color: #a8abb2;
  }
  .class-select {
    box-sizing: border-box;
    padding: 11.5px 32px;
    border-radius: 4px;
    background-color: #f2f4f9;
  }
  .student-select {
    box-sizing: border-box;
    padding: 7.5px 20px;
    border-radius: 4px;
    background-color: #f2f4f9;
  }
  .class-select-active,
  .student-select-active {
    color: @color-brand-regular;
    background-color: rgba(66, 143, 255, 0.2);
  }
  .class-box {
    .tool-box {
      margin-bottom: 16px;
    }
  }
  .class-list,
  .layer-list {
    display: flex;
    flex-wrap: wrap;
    margin-top: 10px;
    margin-bottom: 30px;
    gap: 14px 16px;
  }
  .student-box {
    .student-list {
      :deep(.el-scrollbar__view) {
        display: flex;
        flex-wrap: wrap;
        margin-top: 10px;
        margin-bottom: 20px;
        gap: 14px 16px;
      }
    }
  }
  .list-box {
    height: calc(100% - 65px);
    align-items: self-start;
    .box-left {
      width: 120px;
      height: 97.8%;
      margin-top: 3px;
      overflow-y: auto;
      border-right: 1px solid rgba(4, 11, 26, 0.15);
      .list-item {
        position: relative;
        width: 100%;
        margin-bottom: 50px;
        text-align: left;
        overflow: unset;
        overflow-x: clip;
        .dot {
          position: absolute;
          top: 4px;
          right: 10px;
          z-index: 1;
          width: 18px;
          height: 18px;
          line-height: 18px;
          text-align: center;
          color: #fff;
          font-size: 10px;
          border-radius: 100%;
          background-color: @color-brand-regular;
        }
      }
      .list-item-active {
        color: @color-brand-regular;
      }
      &::-webkit-scrollbar {
        width: 5px;
      }
    }
    .box-right {
      flex: 1;
      box-sizing: border-box;
      padding: 0 0 10px 30px;
      .tool-box {
        margin-bottom: 16px;
      }
    }
  }
  .tool-box {
    :deep(.el-checkbox) {
      .el-checkbox__label {
        font-size: 18px;
      }
    }
  }
}
</style>
